package subscribe

import (
	"fmt"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"os"
	"time"
)

const (
	ModbusStatusTopic = "modbus/slave/status"
)

func NewMqttSubscribeServer() mqtt.Client {
	opts := mqtt.NewClientOptions().AddBroker("tcp://localhost:1883").
		SetUsername("go-test-subscribe").
		SetPassword("123456")

	opts.SetKeepAlive(60 * time.Second)
	opts.SetPingTimeout(1 * time.Second)
	c := mqtt.NewClient(opts)
	if token := c.Connect(); token.Wait() && token.Error() != nil {
		panic(token.Error())
	}

	// 订阅主题
	if token := c.Subscribe(ModbusStatusTopic, 0, SlaveStatusHandle); token.Wait() && token.Error() != nil {
		fmt.Println(token.Error())
		os.Exit(1)
	}

	return c
}

func SlaveStatusHandle(client mqtt.Client, msg mqtt.Message) {
	fmt.Printf("TOPIC: %s\n", msg.Topic())
	fmt.Printf("MSG: %s\n", msg.Payload())
}
